package pw.yitree.work.mmsh.action;

import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.google.gson.Gson;

import pw.yitree.work.mmsh.EnumItem;
import pw.yitree.work.mmsh.HibernateUtil;

/**
 * Servlet implementation class EnumItemServlet
 */
@WebServlet("/data-dictionary")
public class EnumItemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public EnumItemServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String category = request.getParameter("cat");
		String id = request.getParameter("id");
		Gson gson = new Gson();
		//response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		if (id != null && id.length() > 0) {
			EnumItem item = null;
			SessionFactory factory = HibernateUtil.getFactory();
			try (Session session = factory.openSession()) {
				session.getTransaction().begin();
				item = session.get(EnumItem.class, UUID.fromString(id));

				session.getTransaction().commit();
			}

			response.getWriter().append(gson.toJson(item));
		} else {
			List list = null;
			SessionFactory factory = HibernateUtil.getFactory();
			try (Session session = factory.openSession()) {
				session.getTransaction().begin();
				Query q = session.createQuery("from EnumItem where category=:name");
				q.setString("name", category);
				list = q.list();
				session.getTransaction().commit();
			}

			response.getWriter().append(gson.toJson(list));
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
